#include "CMesh.h"

CMesh::CMesh()
{
	pMesh = NULL;
}

CMesh::~CMesh()
{
	if( pMesh != NULL )
		pMesh->Release(); 

	/*
		I seem to have an inheritance problem when is comes to deleting the objects memory. It seems that it already gets deleted
		in the YarnBall class where I make this exact same call. The computer must be calling both destructors. I comment out
		the one in YarnBall. (I don't really know if that's what's going on but it seems that way)
	*/
}

void CMesh::Load(std::string filename, LPDIRECT3DDEVICE9 d3ddev )
{
	if( FAILED( D3DXLoadMeshFromX(filename.c_str(), D3DUSAGE_WRITEONLY, d3ddev, NULL, NULL, NULL, NULL, &pMesh) ) )
		_cprintf("\nFailed to load Mesh!\n");

	LPDIRECT3DVERTEXBUFFER9 vb;
	pMesh->GetVertexBuffer(&vb);
	
}

void CMesh::Render(LPDIRECT3DDEVICE9 d3ddev)
{
	D3DXMATRIXA16 matWorld;
	D3DXMATRIXA16 matTrans;
	D3DXMATRIXA16 matRot;
	D3DXMATRIXA16 matScale;

	

	if( phys_body != NULL )
	{
		D3DXMatrixTranslation( &matTrans, phys_body->GetPosition().x, phys_body->GetPosition().y, z-layer );
		D3DXMatrixScaling( &matScale, sx, sy, sz );
		D3DXMatrixRotationYawPitchRoll( &matRot, 
			                            D3DXToRadian(yaw), 
			                            D3DXToRadian(pitch), 
										phys_body->GetAngle() );
	}
	else
	{
		D3DXMatrixTranslation( &matTrans, x, y, z-layer );
		D3DXMatrixScaling( &matScale, sx, sy, sz );
		D3DXMatrixRotationYawPitchRoll( &matRot, 
			                            D3DXToRadian(yaw), 
			                            D3DXToRadian(pitch), 
			                            D3DXToRadian(roll) );
	}

	matWorld = matRot * matScale * matTrans * cameraMatrix;

	d3ddev->SetTransform( D3DTS_WORLD, &matWorld );

	if( texture != NULL )
	d3ddev->SetTexture(0, this->texture->GetTexture());

	if( pMesh != NULL )
	pMesh->DrawSubset(0);
}